import requests
import toml
import json


class Network():

    addr = "http://"+toml.load("config.toml")["ip"]+":8888"

    def __init__(self) -> None:

        pass

    @classmethod
    def login(cls, username, password):

        resp = requests.get(cls.addr+"/user", params={
            "username": username,
            "password": password,
        })
        if resp.json()["ok"] == True:
            return True
        else:
            return False

    @classmethod
    def reg(cls, username, password, phone, addr):
        resp = requests.post(cls.addr+"/user", data={
            "username": username,
            "password": password,
            "phone": phone,
            "addr": addr,
        })
        if resp.json()["ok"] == True:
            return True
        else:
            print(resp.json())
            return False

    @classmethod
    def find_user_info(cls, username):
        resp = requests.get(cls.addr+"/userinfo", params={
            "username": username,
        })
        if resp.json()["ok"] == True:
            return json.loads(resp.json()["data"])
        else:
            print(resp.json())
            return

    @classmethod
    def modify_user_info(cls, username, password, phone, addr):
        resp = requests.put(cls.addr+"/user", data={
            "username": username,
            "password": password,
            "phone": phone,
            "addr": addr,
        })
        if resp.json()["ok"] == True:
            return
        else:
            print(resp.json())
            return

    @classmethod
    def getGoods(cls, keywords):
        resp = requests.get(cls.addr + "/searchgoods", params={
            "keywords": keywords,
        })
        print(resp)
        if resp.json()["ok"] == True:
            return json.loads(resp.json()["data"])
        else:
            return []

    @classmethod
    def getGoods_username(cls, username):
        resp = requests.get(cls.addr + "/goods", params={
            "ower": username,
        })
        if resp.json()["ok"] == True:
            return json.loads(resp.json()["data"])
        else:
            return []


if __name__ == "__main__":
    print(Network.getGoods("任泽轩"))
